package com.yanming.demo.core.advice;
import com.yanming.demo.core.response.RestResult;
import com.yanming.demo.core.response.RestResultPageDatatables;
import com.yanming.demo.core.response.RestResultPageJqGrid;
import com.yanming.demo.core.response.RestResultPageLayui;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class RestResponseAdvice extends ControllerAdviceMethod implements ResponseBodyAdvice{
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 注意，这里必须返回true，否则不会执行beforeBodyWrite方法
        return supportsMethod(returnType,converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果是返回客户端模板类不进行过滤
        if (body instanceof String || body instanceof RestResult || body instanceof RestResultPageLayui || body instanceof RestResultPageJqGrid || body instanceof RestResultPageDatatables){
            return body;
        }else  if ( body instanceof Byte || body instanceof Short || body instanceof Integer || body instanceof Long || body instanceof Float || body instanceof Double || body instanceof Boolean  ) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("result", body);
            return new RestResult(0,"成功",map);
        }else{
            return new RestResult(0,"成功",body);
        }
    }
}
